package org.michael.u.brg.by.spring.aop.abcthreads;

import java.util.concurrent.ExecutorService;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Entry point into the application
 */
public class Startup implements ApplicationContextAware, Runnable {
	
	private ApplicationContext springAppcontext;
	
	public Startup() {	}

	public void run() {
        RunnerA a = (RunnerA) springAppcontext.getBean("a");
        ExecutorService exec = (ExecutorService) springAppcontext.getBean("exec");
		exec.execute(a); // spawn the A runner
	}

    /**
     * Spring will call this method as an init method to the bean.
     */
    public void init() {
        Thread myself = new Thread(this, "Startup thread");
        myself.setDaemon(true); // never mind this thread as long as others are done
        System.out.printf("%n-- Startup ran!");
		IdProvider provider = (IdProvider)springAppcontext.getBean("idProvider");
		System.out.printf("%n%d, %d, %d", provider.getNext(), provider.getNext(), provider.getNext());
		ExecutorService exec = (ExecutorService) springAppcontext.getBean("exec");
        exec.execute(myself);
    }
    /**
     * That's all you need to run a Spring beans driven app. Spring will create an initialize all the rest.
     */
	@SuppressWarnings({"JavaDoc"})
    public static void main(String[] args) {
		new ClassPathXmlApplicationContext("org/michael/u/brg/by/spring/aop/abcthreads/beans.xml");
	}

    /**
     * Spring framework will call every bean that implements {@link org.springframework.context.ApplicationContextAware}
     * interface and pass the app context for the arg. 
     */
	public void setApplicationContext(ApplicationContext value)
			throws BeansException {
		springAppcontext = value;
	}

}
